import { useEffect, useState } from 'react';
import Taro, { FC } from '@tarojs/taro';
import { Subject, Subscription } from 'rxjs';
import { debounceTime, switchMap } from 'rxjs/operators';
import { AtInput, AtForm, AtIcon, AtListItem, AtList } from "taro-ui"
import "taro-ui/dist/style/components/image-picker.scss";
import { View, Text, Image } from '@tarojs/components'
import "taro-ui/dist/style/components/button.scss" // 按需引入 
import { useAuthFacade } from '@/hooks/useAuthFacade';
import { onEmit } from '@/utils/rxHelpers';
import { uploadFile } from "@/utils/qcloudHelpers";
import { getLogger } from '@/utils/log';
import { rsgIdNum, rsgName } from '@/utils/regexRule';
import { ApprovalStatus } from '@/models/request/userReq';
import ChannelStyle from '@@/channel/channelStyle';
import './index.scss'

//个人认证
export const UserVerify: FC = () => {
  const logger = getLogger("/pages/my/userVerify");

  //用不到的变量不用写
  const [authFacade, , , realName, , , , , idCardNo] = useAuthFacade();


  const initSubject = () => new Subject<any>();
  const [emitter, setEmitter] = useState<Subject<any>>(initSubject)

  // 个人信息
  const [inputRealName, setInputRealName] = useState("")
  const [inputIdCardNo, setInputIdCardNo] = useState("")
  const [front, setFront] = useState('')
  const [back, setBack] = useState('')

  //把按钮提交事件转化为observable
  const userApprove$ = emitter.asObservable()
    .pipe(
      //防抖动(防重复)
      debounceTime(400),
      // filter(obj => isPersonApproveParams(obj)),
      // map(obj => obj as PersonApproveParams),
      //接收按钮点击的参数
      switchMap((userApproveObj) => {
        if (!userApproveObj.realName) {
          throw Taro.showToast({
            title: '请输入真实姓名',
            icon: 'none',
            duration: 2000
          })
        }
        // 昵称长度校验
        rsgName(userApproveObj.realName)
        if (!userApproveObj.idCardNo) {
          throw Taro.showToast({
            title: '请输入身份证号码',
            icon: 'none',
            duration: 2000
          })
        }
        rsgIdNum(userApproveObj.idCardNo)
        if (!userApproveObj.idCardFront) {
          throw Taro.showToast({
            title: '请上传证件照信息面',
            icon: 'none',
            duration: 2000
          })

        }
        if (!userApproveObj.idCardBack) {
          throw Taro.showToast({
            title: '请上传证件照国徽面',
            icon: 'none',
            duration: 2000
          })
        }
        return authFacade.personApprove(userApproveObj);
      })
    )

  // 个人信息填写
  const handleChangeName = (value: string) => {
    if (value.length > 20) {
      Taro.showToast({
        title: '请输入2~20个字符',
        icon: 'none',
        duration: 2000
      })
    }
    setInputRealName(value)
  }
  // 校验昵称2~20
  const handleBlurName = (value: string) => {
    rsgName(value)
  }
  const handleChangeIdCard = (value: string) => {

    setInputIdCardNo(value)
  }

  // 删除图片
  const handleDelImg1 = () => {
    setFront('')
  }
  const handleDelImg2 = () => {
    setBack('')
  }

  // 校验身份证
  const handleCheckRule = (value: string) => {
    rsgIdNum(value)
  }
  //返回上一层
  const goBack = () => {
    Taro.showToast({
      title: '保存成功',
      icon: 'none',
      duration: 2000
    }).then(() => {
      setTimeout(() => {
        Taro.redirectTo({
          // url: '/pages/my/editInfo/index'
          url: '/subPages/my/editInfo/index'
        })
      }, 1000)

    })
  }


  const pickImage = (pos: string) => {
    Taro.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有，在H5浏览器端支持使用 `user` 和 `environment`分别指定为前后摄像头
      success: function (res) {
        uploadFile(res.tempFilePaths[0],
          (resUrl: string) => {
            //Fixme， 上传完成之前，都不允许点击保存按钮，否则请求后端的图片参数为空
            // if (type === 'personal') {
            if (pos == "front") {
              setFront(resUrl);
            } else {
              setBack(resUrl);
            }
            // } else {
            // setOrgImg(resUrl);
            // }
          },
          () => { return }
        )
      }
    })
  }

  //FIXME 这里有执行两次的问题，是Taro的bug。等同于Component的componentWillMount
  useEffect(() => {
    //注册并执行所有rxjs流
    const subscriptions: Subscription[] = [
      onEmit<ApprovalStatus>(
        userApprove$,
        () => {
          goBack();
        },
        err => {
          logger.ERROR("保存信息失败！", err);
          setEmitter(initSubject);
        }
      ),
    ]
    //页面销毁时也销毁所有订阅，防止内存泄漏
    return () => { subscriptions.map(sub => sub.unsubscribe()) };
  }, [userApprove$]);

  //更新绑定的值
  useEffect(() => {
    setInputRealName(realName)
    setInputIdCardNo(idCardNo)
  }, [realName, idCardNo]);

  return (
    <View className='index'>
      <View className='main'>
        {/* 提交类型 */}
        <AtList>
          <AtListItem title='信息提交' className='top-title' />
        </AtList>

        {/* 个人认证模块 */}
        <View>
          <AtForm>
            <AtInput
              name='value1'
              title='真实姓名'
              type='text'
              placeholder=''
              value={inputRealName}
              onChange={handleChangeName.bind(this)}
              onBlur={handleBlurName.bind(this)}
              className='text'
            >
              <AtIcon value='chevron-right' size='20' color='#ccc'></AtIcon>
            </AtInput>
            <AtInput
              name='value2'
              title='身份证号码'
              type='idcard'
              placeholder=''
              value={inputIdCardNo}
              onChange={handleChangeIdCard.bind(this)}
              onBlur={handleCheckRule.bind(this)}
              className='text'
            >
              <AtIcon value='chevron-right' size='20' color='#ccc'></AtIcon>
            </AtInput>

            <View className='title'>
              <Text className='push'>上传身份证照片</Text>
            </View>
            {/* 上传身份证正面 */}
            <View className='certificates'>
              <Image src={front} className='pick1' onClick={() => pickImage("front")}></Image>
              <View>
                {front && front.length > 0 && (<View className='icon-del' onClick={handleDelImg1}></View>)}
                {!front && (<Text className='text1'>上传证件照信息面</Text>)}
              </View>
            </View>
            {/* 上传身份证反面 */}
            <View className='certificates'>
              <Image src={back} className='pick2' onClick={() => pickImage("back")}></Image>
              <View>
                {back && back.length > 0 && (<View className='icon-del' onClick={handleDelImg2}></View>)}
                {!back && (<Text className='text1'>上传证件照国徽面</Text>)}
              </View>
            </View>
          </AtForm>
        </View>

        {/* 说明信息 */}
        <View className='tips-msg'>
          <Text>说明：根据国家相关法律法规要求，创建{ChannelStyle.appName}LIVE直播间必须进行实名认证。{ChannelStyle.appName}LIVE承诺认证信息严格保密，未做授权，不将信息另做他用，请放心认证。</Text>
        </View>

        {/* 提交按钮 */}
        <View className='bt' onClick={e => {
          emitter.next({
            idCardNo: inputIdCardNo,
            realName: inputRealName,
            idCardFront: front,
            idCardBack: back
          })
        }}
        >
          <Text>提交认证</Text>
        </View>

      </View>
    </View >
  )
}
export default UserVerify

